package com.atguigu.Flink.timeAndwindow;

import com.atguigu.Flink.POJO.Event;
import com.atguigu.Flink.POJO.WordCount;
import com.atguigu.Flink.function.ClickSource;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.time.Duration;
import java.util.HashSet;

public class Flink06_AggregateFunction {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<Event> ds = env.addSource(new ClickSource()).assignTimestampsAndWatermarks(
                WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ZERO)
                        .withTimestampAssigner(
                                new SerializableTimestampAssigner<Event>() {
                                    @Override
                                    public long extractTimestamp(Event event, long l) {
                                        return event.getTs();
                                    }
                                }
                        )
        );
        ds.print("input");

        //统计10秒内uv(独立访客数)
        ds.windowAll(
                TumblingEventTimeWindows.of(Time.seconds(10))
        ).aggregate(
                new AggregateFunction<Event, HashSet<String>, Integer>() {
                    @Override
                    public HashSet<String> createAccumulator() {
                        return new HashSet<>();
                    }

                    @Override
                    public HashSet<String> add(Event event, HashSet<String> strings) {
                        strings.add(event.getUser());
                        return strings;
                    }

                    @Override
                    public Integer getResult(HashSet<String> strings) {
                        return strings.size();
                    }

                    @Override
                    public HashSet<String> merge(HashSet<String> strings, HashSet<String> acc1) {
                        return null;
                    }
                }
        ).print("window");





        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
